package com.jingdianjichi.wx.cache;

import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

/**
 * 极简内存缓存：键（如微信 MsgId） -> 文本回复，带 TTL。
 * 兼容 JDK 1.8，不使用 record、var 等新语法。
 */
public final class AiCache {

    private static final Map<String, Entry> MAP = new ConcurrentHashMap<String, Entry>();
    private static final long TTL_MS = TimeUnit.MINUTES.toMillis(10);   // 默认 10 分钟
    private static final long CLEANUP_INTERVAL_MS = 60_000L;            // 每 60s 清理一次过期项
    private static volatile long lastCleanupAt = 0L;

    private AiCache() {}

    private static final class Entry {
        final String val;
        final long expireAt;
        Entry(String val, long expireAt) {
            this.val = val;
            this.expireAt = expireAt;
        }
    }

    /** 写入（或覆盖） */
    public static void put(String key, String val) {
        if (key == null || val == null) return;
        long now = System.currentTimeMillis();
        MAP.put(key, new Entry(val, now + TTL_MS));
        cleanupIfNeeded(now);
    }

    /** 读取；过期则返回 null 并移除 */
    public static String get(String key) {
        if (key == null) return null;
        long now = System.currentTimeMillis();
        Entry e = MAP.get(key);
        if (e == null) return null;
        if (now > e.expireAt) {
            MAP.remove(key);
            return null;
        }
        cleanupIfNeeded(now);
        return e.val;
    }

    /** 简单的定期清理（惰性触发，避免额外线程） */
    private static void cleanupIfNeeded(long now) {
        if (now - lastCleanupAt < CLEANUP_INTERVAL_MS) return;
        synchronized (AiCache.class) {
            if (now - lastCleanupAt < CLEANUP_INTERVAL_MS) return;
            Iterator<Map.Entry<String, Entry>> it = MAP.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry<String, Entry> en = it.next();
                if (now > en.getValue().expireAt) it.remove();
            }
            lastCleanupAt = now;
        }
    }
}
